package tt.dz.appserver.mvc.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

import tt.dz.appserver.util.WebSocketUtils;

//@WebListener
@ServerEndpoint("/static/websocket/{userId}") 
public class WebSocketServer {
	private static final Logger LOG = Logger.getLogger(WebSocketServer.class);
	
	//private static Map<String, Session> sessionMap=new HashMap<String, Session>();//在线的客户端session集合，只在第一次new的时候初始化。  
	  /** 
	   * 接收信息事件 
	   * @param message 客户端发来的消息 
	   * @param session 当前会话 
	   */  
	  @OnMessage  
	  public void onMessage(String message,Session session,@PathParam(value="userId")String userId)throws Exception {  
	     
	    try {  
	        Iterator<String> it = WebSocketUtils.clients.keySet().iterator();  
	        //循环给每个客户端发送信息  
	        while(it.hasNext()){  
	            String key = (String) it.next();  
	            Session value = WebSocketUtils.clients.get(key);  
	            value.getBasicRemote().sendText(message);  
	        }  
	        LOG.info("用户"+userId+"说："+message+"。");  
	        LOG.info("当前在线人数："+ WebSocketUtils.clients.size());  
	    } catch (Exception e) { 
	    	LOG.info("接收消息事件异常!"); 
	    	LOG.info(e.getMessage());  
	    }  
	  }  
	    
	  /** 
	   * 打开连接事件 
	 * @throws Exception  
	   */  
	  @OnOpen  
	  public void onOpen(Session session,@PathParam(value="userId")String userId) throws Exception {  
		  LOG.info("打开连接成功！");  
		  WebSocketUtils.clients.put(userId, session);  
	      LOG.info("用户"+userId+"进来了。。。");  
	      LOG.info("当前在线人数："+ WebSocketUtils.clients.size());  
	  }  
	   
	  /** 
	   * 关闭连接事件 
	   */  
	  @OnClose  
	  public void onClose(Session session,@PathParam(value="userId")String userId) {  
		  LOG.info("关闭连接成功！");  
		  LOG.info("用户"+userId+"离开了。。。");  
		  WebSocketUtils.clients.remove(userId);  
	      LOG.info("当前在线人数："+ WebSocketUtils.clients.size());  
	  }  
	    
	  /** 
	   * 错误信息响应事件 
	   * @param session 
	   * @param throwable 
	   */  
	  @OnError
	  public void onError(Session session,Throwable throwable,@PathParam(value="userId")String userId) {  
		  LOG.info("异常："+throwable.getMessage());  
		  LOG.info("用户"+userId+"的连接出现了错误。。。");  
		  LOG.info("当前在线人数："+ WebSocketUtils.clients.size());  
	  }  
	  
	  
}
